import { constantRoutes } from '@/router'
import { asyncRouterMap } from '@/router/routers'
import Layout from '@/layout/index'
import { log } from '@/utils/log'

const state = {
  routers: constantRoutes,
  addRouters: [],
  isAddRoute: false,
  menus: []
}
const formatRoutesMap = []
const formatMenusMap = []
const mutations = {
  SET_ROUTERS: (state, auth) => {
    const routers = auth.routers
    state.addRouters = routers
    state.routers = constantRoutes.concat(routers)
    state.isAddRoute = true
    state.menus = auth.menus
  }
}
const actions = {
  GenerateRoutes({ commit }, routes) {
    return new Promise(resolve => {
      formatRoutes(routes, undefined)
      formatMenus(routes, formatMenusMap)
      commit('SET_ROUTERS', {
        routers: [
          {
            path: '/',
            component: Layout,
            children: formatRoutesMap
          },
          { path: '*', redirect: '/404', hidden: true }
        ],
        menus: formatMenusMap
      })
      resolve()
    })
  }
}

// 组合路由
const formatRoutes = (routes, pid) => {
  routes.forEach((route, index) => {
    var findRouter = asyncRouterMap[route.name]
    if (findRouter !== undefined) {
      formatRoutesMap.push({
        path: findRouter.path,
        name: route.name,
        component: findRouter.component
      })
    }
    if (route.children.length > 0) {
      formatRoutes(route.children, index)
    }
  })
}

// 根据接口获取的菜单，重新组合
const formatMenus = (menus, resData) => {
  if (Array.isArray(menus) && menus.length > 0) {
    menus.forEach((menu, index) => {
      const findRouter = asyncRouterMap[menu.name]
      // /id是一个随机数，主要是给sidebar中:key使用
      const path = findRouter === undefined ? ('/' + menu.id) : findRouter.path
      const temp = {
        meta: {
          title: menu.title,
          icon: menu.icon
        },
        id: menu.id,
        path: path,
        hidden: !menu.is_menu
      }
      resData[index] = temp
      var arr = []
      formatMenus(menu.children, arr)
      resData[index].children = arr
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
